import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';
import LanguageSelector from '../components/LanguageSelector';
import LoginModal from '../components/LoginModal';
import ContactUsModal from '../components/ContactUsModal';
import LogoutConfirmModal from '../components/LogoutConfirmModal';
import { useUserProfile } from '../hooks/useUserProfile';
import { useChatHistoryManager } from '../hooks/useChatHistoryManager';
import { getDynamicFonts } from '@/utils/fontUtils';
import ptVip from '@/assets/images/sidbar/1.webp';
import xyVip from '@/assets/images/sidbar/2.webp';
import zzVip from '@/assets/images/sidbar/3.webp';

// 菜单项配置
const menuItems = [
    {
        key: 'Explore',
        icon: 'fas fa-compass',
        labelKey: 'Explore',
        path: '/',
    },
    {
        key: 'chatCollection',
        icon: 'fas fa-comments',
        labelKey: 'chatCollection',
        path: '/chat-collection',
    },
    {
        key: 'generateImage',
        icon: 'fas fa-image',
        labelKey: 'generateImage',
        path: '/collections',
    },
    // {
    //     key: 'createCharacter',
    //     icon: 'fas fa-user-plus',
    //     labelKey: 'createCharacter',
    //     path: '/create-character',
    // },
    // {
    //     key: 'myAi',
    //     icon: 'fas fa-robot',
    //     labelKey: 'myAi',
    //     path: '/my-ai',
    // },
    {
        key: 'becomePremium',
        icon: 'fas fa-crown',
        labelKey: 'becomePremium',
        path: '/subscriptions',
    },
    {
        key: 'buyToken',
        icon: 'fas fa-coins',
        labelKey: 'common.buyToken',
        path: '/buygems',
    },
];

interface SidebarProps {
    sidebarCollapsed: boolean;
    isMobile: boolean;
    activeTab: string;
    setActiveTab: (tab: string) => void;
    onCloseSidebar?: () => void; // 新增：关闭侧边栏的回调
    onChatCollectionClick?: () => void; // 新增：处理聊天收藏点击的回调（用于AvatarModal场景）
}

// 工具函数：头像图片拼接
function withAvatarResize(url?: string | null): string {
    if (!url) return '';
    if (url.includes('x-oss-process=image/resize')) return url;
    if (/^https?:\/\//.test(url)) {
        return url + (url.includes('?') ? '&' : '?') + 'x-oss-process=image/resize,w_300';
    }
    return url;
}

const Sidebar: React.FC<SidebarProps> = ({ sidebarCollapsed, isMobile, activeTab, setActiveTab, onCloseSidebar, onChatCollectionClick }) => {
    const { t, i18n } = useTranslation();
    const navigate = useNavigate();
    const location = useLocation();

    // 根据当前语言动态获取字体
    const dynamicFonts = getDynamicFonts(i18n);
    const [hovered, setHovered] = useState<string | null>(null);
    const [userMenuOpen, setUserMenuOpen] = useState(false);
    const [showContactUsModal, setShowContactUsModal] = useState(false);
    const {
        isLoggedIn,
        userData,
        showLoginModal,
        isRegisterMode,
        handleLogoutClick,
        withAvatarResize,
        closeLoginModal,
        openLoginModal,
        handleLoginSuccessAndUpdateTab,
        showLogoutConfirm,
        confirmLogout,
        cancelLogout
    } = useUserProfile();
    const { loadLatestChatFromHistory } = useChatHistoryManager();

    // 包装登录成功处理，传入setActiveTab
    const handleLoginSuccess = () => {
        handleLoginSuccessAndUpdateTab(setActiveTab);
    };

    // Check if user is logged in (removed - now using useAuth hook)

    // 检查登录状态并显示登录弹窗（如果未登录）
    const checkLoginAndShowModal = () => {
        if (!isLoggedIn) {
            openLoginModal(false);
            return false;
        }
        return true;
    };

    // 判断当前菜单项是否激活
    const isActive = (item: typeof menuItems[0]) => {
        const currentPath = location.pathname;
        if (item.key === 'Explore') {
            return currentPath === '/';
        }
        return currentPath === item.path;
    };

    // Handle chat menu item click
    const handleChatClick = async (e: React.MouseEvent, path: string) => {
        if (path === '/chat-collection') {
            e.preventDefault();

            // 检查用户是否登录
            if (!checkLoginAndShowModal()) {
                return;
            }

            try {
                // 使用新的API方式获取最新聊天记录
                const result = await loadLatestChatFromHistory();
                // console.log('result', result);

                if (isMobile) {
                    // 如果在AvatarModal中且有回调函数，则调用回调
                    if (onChatCollectionClick) {
                        onChatCollectionClick();
                    } else {
                        // 如果有最新聊天，跳转到聊天页面，否则不做任何操作
                        if (Array.isArray(result) && result.length > 0) {
                            const firstChat = result[0];
                            // 保存当前对话ID到sessionStorage
                            sessionStorage.setItem('currentConversationId', firstChat.id);
                            navigate('/conversation');
                            if (onCloseSidebar) {
                                onCloseSidebar();
                            }
                        } else {
                            // console.log('移动端：没有聊天历史，不进行跳转');
                        }
                    }
                    return;
                } else {
                    // PC端逻辑：如果有最新聊天，跳转到聊天页面
                    if (Array.isArray(result) && result.length > 0) {
                        const firstChat = result[0];
                        // 保存当前对话ID到sessionStorage
                        sessionStorage.setItem('currentConversationId', firstChat.id);
                        navigate('/conversation');
                    } else {
                        // console.log('PC端：没有聊天历史，不进行跳转');
                    }
                }
            } catch (error) {
                // console.error('❌ 获取聊天历史失败:', error);
                console.error('loadLatestChatFromHistory failed', error);
                // 可以在这里添加错误提示
            }
        }
    };

    // Handle Explore menu item click
    const handleExploreClick = (e: React.MouseEvent) => {
        e.preventDefault();
        // 直接跳转到首页，不使用浏览器回退功能
        navigate('/');
        // 如果在移动端，关闭侧边栏
        if (isMobile && onCloseSidebar) {
            onCloseSidebar();
        }
    };

    // Handle Contact Us click
    const handleContactUsClick = (e: React.MouseEvent) => {
        e.preventDefault();
        if (checkLoginAndShowModal()) {
            setShowContactUsModal(true);
        }
    };

    // 只根据 props 控制 UI 展示，不做动画和宽度切换
    // 移动端收起时直接隐藏
    if (isMobile && !sidebarCollapsed) return null;

    return (
        <>
            <aside
                className={`h-[calc(100vh-3.8rem)] border-r border-[rgb(54,54,54)] flex flex-col fixed left-0 z-[99] bg-[rgb(19,19,19)]`}
                style={{
                    minWidth: sidebarCollapsed ? 200 : isMobile ? 0 : 80,
                    height: `calc(100dvh - 3.2rem)`,
                    paddingBottom: 'env(safe-area-inset-bottom, 0px)',
                    fontFamily: dynamicFonts.font2,
                    width: sidebarCollapsed ? '14rem' : isMobile ? 0 : '5rem',
                    display: (isMobile && !sidebarCollapsed) ? 'none' : 'flex',
                }}
            >
                {/* 菜单列表+用户头像（移动端） */}
                <nav className="flex-1 flex flex-col py-2 space-y-2 md:py-4">
                    {/* 移动端头像+下拉菜单 */}
                    {isMobile && isLoggedIn && (
                        <div className="flex flex-col items-stretch">
                            <div
                                className="flex items-center px-4 py-2  cursor-pointer border-b border-[rgb(54,54,54)] hover:bg--600/20"
                                onClick={() => setUserMenuOpen((open) => !open)}
                            >
                                <div className="w-6 h-6 rounded-full overflow-hidden border-2 border-pink-500 flex-shrink-0">
                                    {userData?.user_avatar ? (
                                        <img src={withAvatarResize(userData.user_avatar)} alt="avatar" className="w-full h-full object-cover" />
                                    ) : (
                                        <div className="w-full h-full bg-gray-600 flex items-center justify-center animate-pulse">
                                            <i className="fas fa-user text-gray-400 text-xl"></i>
                                        </div>
                                    )}
                                </div>
                                <span className="ml-3 text-base font-medium whitespace-nowrap text-white">{userData?.user_displayName || t('common.welcome')}</span>
                                <i className={`fas fa-chevron-${userMenuOpen ? 'up' : 'down'} ml-auto text-xs text-gray-400`} />
                            </div>
                            {/* 用户子菜单 */}
                            {userMenuOpen && (
                                <div style={{ fontFamily: dynamicFonts.font3 }} className=" w-full mt-2 rounded-lg shadow-lg text-center animate-fade-in">

                                    {/* <div
                                        className="w-full py-2 text-white hover:bg-pink-600/20 transition-colors cursor-pointer flex items-center justify-start px-4"
                                        onClick={() => { navigate('/buygems'); }}
                                    >
                                        <div style={{ width: "2.1rem" }}>
                                            <i className="fas fa-crown text-xl ml-0 mr-3 text-yellow-400" />
                                        </div>
                                        <span style={{ fontSize: "0.9rem" }}>  {t('Subscription')}  </span>
                                    </div> */}
                                    {/* 跳转到设置页面 */}
                                    {/* <div
                                        className="w-full py-2 text-white hover:bg-pink-600/20 transition-colors cursor-pointer flex items-center justify-start px-4"
                                        onClick={() => { }}
                                    >
                                        <div style={{ width: "2.1rem" }}>
                                            <i className="fas fa-cog text-xl ml-1 mr-3 text-gray-300" />
                                        </div>
                                        <span style={{ fontSize: "0.9rem" }}>  {t('Settings')}  </span>
                                    </div> */}
                                    <div
                                        className="w-full py-2 text-red-400 hover:bg-red-600/20 transition-colors cursor-pointer flex items-center justify-start px-4"
                                        onClick={handleLogoutClick}
                                    > <div style={{ width: "2.1rem" }}>
                                            <i className="fas fa-sign-out-alt ml-1 text-xl mr-3 text-red-400" />
                                        </div>
                                        <span style={{ fontSize: "0.9rem" }}>  {t('common.logout')}  </span>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                    {/* 普通菜单项 */}
                    {menuItems.map((item) => {
                        const active = isActive(item);
                        return (
                            <a
                                key={item.key}
                                href={item.path}
                                onClick={
                                    item.key === 'Explore'
                                        ? handleExploreClick
                                        : item.key === 'becomePremium'
                                            ? (e) => {
                                                e.preventDefault();
                                                if (checkLoginAndShowModal()) {
                                                    navigate('/subscriptions');
                                                }
                                            }
                                            : item.key === 'buyToken'
                                                ? (e) => {
                                                    e.preventDefault();
                                                    if (checkLoginAndShowModal()) {
                                                        navigate('/buygems');
                                                    }
                                                }
                                                : item.key === 'createCharacter'
                                                    ? async (e) => {
                                                        e.preventDefault();
                                                        // 新增：判断登录，未登录弹出登录弹窗
                                                        if (!checkLoginAndShowModal()) {
                                                            return;
                                                        }
                                                        // 已登录，使用新的API方式获取最新聊天记录
                                                        try {
                                                            const result = await loadLatestChatFromHistory();
                                                            if (result.chatId) {
                                                                // console.log(`🎯 跳转到最新聊天: ${result.chatId}`);
                                                                // 保存当前对话ID到sessionStorage
                                                                sessionStorage.setItem('currentConversationId', result.chatId);
                                                                navigate('/conversation');
                                                            } else {
                                                                // console.log('💡 没有聊天历史，跳转到首页');
                                                                navigate('/');
                                                            }
                                                        } catch (error) {
                                                            // console.error('❌ 获取最新聊天记录失败:', error);
                                                            console.error('loadLatestChatFromHistory failed', error);
                                                            // 发生错误时跳转到首页
                                                            navigate('/');
                                                        }
                                                        if (isMobile && onCloseSidebar) {
                                                            onCloseSidebar();
                                                        }
                                                    }
                                                    : item.key === 'generateImage'
                                                        ? (e) => {
                                                            e.preventDefault();
                                                            // 新增：判断登录，未登录弹出登录弹窗
                                                            if (!checkLoginAndShowModal()) {
                                                                return;
                                                            }
                                                            navigate('/collections');
                                                            if (isMobile && onCloseSidebar) {
                                                                onCloseSidebar();
                                                            }
                                                        }
                                                        : (e) => handleChatClick(e, item.path)
                                }
                                className={`${!isMobile ? (sidebarCollapsed ? 'w-[80%] ml-[10%]' : 'w-[55%] ml-[22.5%]') + ' rounded-lg border border-[rgb(54,54,54)] px-3 py-2' : 'border-b border-[rgb(54,54,54)] rounded-none px-5 py-2'} flex items-center ${sidebarCollapsed ? 'justify-start' : 'justify-center'} transition-colors duration-200 cursor-pointer group relative`}
                                style={{
                                    fontFamily: dynamicFonts.font3,
                                    // 默认颜色会被下面的条件覆盖
                                    ...(!(active || (item.key === 'becomePremium' && userData && userData.vip_live) ||
                                        ((item.key === 'becomePremium' || item.key === 'buyToken') && (!active && (!hovered || isMobile || hovered !== item.key)))) ?
                                        { color: 'rgb(209,209,209)' } : {}),
                                    // 激活状态的背景色优先级最高
                                    ...(active ? {
                                        backgroundColor: 'rgb(63,63,70)',
                                        color: (item.key === 'becomePremium' && userData && userData.vip_live) ? '#131313' :
                                            (item.key === 'becomePremium' || item.key === 'buyToken') ? 'rgb(252,118,138)' : 'white'
                                    } : {}),
                                    // hover 状态仅在非激活时生效
                                    ...((!active && !isMobile && hovered === item.key) ? {
                                        backgroundColor: 'rgb(63,63,70)',
                                        color: (item.key === 'becomePremium' && userData && userData.vip_live) ? '#131313' :
                                            (item.key === 'becomePremium' || item.key === 'buyToken') ? 'rgb(252,118,138)' : 'white'
                                    } : {}),
                                    // becomePremium 和 buyToken 特殊颜色处理
                                    ...((item.key === 'becomePremium' && userData && userData.vip_live) ?
                                        { color: '#131313' } :
                                        ((item.key === 'becomePremium' || item.key === 'buyToken') && (!active && (!hovered || isMobile || hovered !== item.key)) ?
                                            { color: 'rgb(252,118,138)' } : {})),
                                }}
                                onMouseEnter={() => !isMobile && setHovered(item.key)}
                                onMouseLeave={() => !isMobile && setHovered(null)}
                            >
                                <div className="flex items-center justify-center" style={{ width: !isMobile && !sidebarCollapsed && item.key === 'becomePremium' && userData && userData.vip_live ? "2.1rem" : "1.4rem" }}>
                                    {item.key === 'becomePremium' && userData && userData.vip_live ? (
                                        <>
                                            {userData.vip_live === 1 && <img src={ptVip} alt="PT VIP" className="w-8 h-6" style={{ objectFit: 'contain', maxWidth: !isMobile && !sidebarCollapsed ? '150%' : '100%', width: !isMobile && !sidebarCollapsed ? '150%' : undefined }} />}
                                            {userData.vip_live === 2 && <img src={xyVip} alt="XY VIP" className="w-6 h-6" style={{ objectFit: 'contain', maxWidth: !isMobile && !sidebarCollapsed ? '150%' : '100%', width: !isMobile && !sidebarCollapsed ? '150%' : undefined }} />}
                                            {userData.vip_live === 3 && <img src={zzVip} alt="ZZ VIP" className="w-6 h-6" style={{ objectFit: 'contain', maxWidth: !isMobile && !sidebarCollapsed ? '150%' : '100%', width: !isMobile && !sidebarCollapsed ? '150%' : undefined }} />}
                                        </>
                                    ) : (
                                        <i className={`${item.icon} ${isMobile ? 'text-xl' : sidebarCollapsed ? 'text-[1rem]' : 'text-[1.4rem]'}`} />
                                    )}
                                </div>
                                {sidebarCollapsed && (
                                    <span className="ml-2 text-[0.78rem] font-medium whitespace-nowrap" style={item.key === 'becomePremium' && userData && userData.vip_live ? { color: '#e5e7eb' } : {}}>
                                        {item.key === 'becomePremium' && userData && userData.vip_live ? t('subscription.upgrade') : t(item.labelKey)}
                                    </span>
                                )}
                                {/* 收起时气泡提示 */}
                                {!sidebarCollapsed && hovered === item.key && (
                                    <span className="absolute left-full top-1/2 -translate-y-1/2 ml-2 px-3 py-1 bg-gray-900 text-xs rounded shadow-lg whitespace-nowrap animate-fade-in pointer-events-none" style={item.key === 'becomePremium' && userData && userData.vip_live ? { color: '#e5e7eb' } : { color: 'white' }}>
                                        {item.key === 'becomePremium' && userData && userData.vip_live ? t('subscription.upgrade') : t(item.labelKey)}
                                    </span>
                                )}
                            </a>
                        );
                    })}
                </nav>

                {/* 侧边栏底部功能区 */}
                <div className="px-4 pb-8 pt-6" style={{ borderTop: "1px solid rgb(66,66,66)" }}>
                    {/* 上部分：语言切换和Contact Us */}
                    {sidebarCollapsed ? (
                        <div style={{ fontFamily: dynamicFonts.font3 }} className={`mb-2 flex ${isMobile ? 'flex-row gap-2' : 'flex-col gap-2'}`}>
                            <div
                                className="flex-1 rounded-lg border border-[rgb(54,54,54)] px-2 py-2 flex items-center justify-center text-[0.8rem] cursor-pointer transition-colors"
                                style={{ ...((!isMobile && hovered === 'lang') ? { backgroundColor: 'rgb(63,63,70)' } : {}), width: "98%", margin: "auto" }}
                                onMouseEnter={() => !isMobile && setHovered('lang')}
                                onMouseLeave={() => !isMobile && setHovered(null)}
                            >
                                <LanguageSelector jx={true} className="w-full" onLanguageChange={isMobile ? onCloseSidebar : undefined} />
                            </div>
                            <div
                                className="flex-1 rounded-lg border border-[rgb(54,54,54)] px-2 py-2 text-[rgb(209,209,209)] text-left cursor-pointer transition-colors flex items-center text-[0.8rem] truncate"
                                style={{
                                    color: 'rgb(209,209,209)',
                                    ...((!isMobile && hovered === 'contact') ? { backgroundColor: 'rgb(63,63,70)' } : {})
                                }}
                                onMouseEnter={() => !isMobile && setHovered('contact')}
                                onMouseLeave={() => !isMobile && setHovered(null)}
                                onClick={handleContactUsClick}
                            >
                                {!isMobile && <i className="fas fa-envelope text-[1rem] mr-2"></i>}
                                {t('contactUs.title')}
                            </div>
                        </div>
                    ) : (
                        <div className="mb-2 flex flex-col items-center gap-4">
                            {/* 语言icon */}
                            <div className={`${!isMobile ? (sidebarCollapsed ? 'w-[85%] ml-[7.5%]' : 'w-[85%] ml-[7.5%]') + ' rounded-lg border border-[rgb(54,54,54)] px-3 py-2' : 'border-b border-gray-600 rounded-none px-8 py-2'} flex items-center justify-center`} title={t('common.language')} style={{ color: 'rgb(209,209,209)' }}>
                                {(() => {
                                    const isDevelopment = import.meta.env.DEV || import.meta.env.MODE === 'development';
                                    const lang = (typeof window !== 'undefined' && window.localStorage.getItem('i18nextLng')) || 'ja';

                                    // 在生产环境下，如果语言是中文，显示日文图标
                                    if (!isDevelopment && lang.startsWith('zh')) return '🇯🇵';
                                    if (lang.startsWith('zh')) return '🇨🇳';
                                    if (lang.startsWith('ja')) return '🇯🇵';
                                    return '🇺🇸';
                                })()}
                            </div>
                            {/* 联系我们icon */}
                            <div
                                className={`${!isMobile ? (sidebarCollapsed ? 'w-[85%] ml-[7.5%]' : 'w-[85%] ml-[7.5%]') + ' rounded-lg border border-[rgb(54,54,54)] px-3 py-2' : 'border-b border-gray-600 rounded-none px-8 py-2'} flex items-center justify-center`}
                                title="Contact Us"
                                style={{ color: 'rgb(209,209,209)' }}
                                onClick={handleContactUsClick}
                            >
                                {(!isMobile || sidebarCollapsed) && <i className="fas fa-envelope text-[1.4rem] "></i>}
                                {(sidebarCollapsed) &&
                                    <span>{t('contactUs.title')}</span>
                                }
                            </div>
                        </div>
                    )}
                    {/* 最底部：隐私和条款 */}
                    {sidebarCollapsed ? (
                        <div className="flex flex-row items-center justify-left text-[0.6rem] space-x-2 mt-4 w-full overflow-hidden" style={{ color: 'rgb(209,209,209)', fontFamily: dynamicFonts.font2 }}>
                            <a href="/document/privacy" target="_blank" rel="noopener noreferrer" className="truncate max-w-[90px]" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'inline-block', color: 'rgb(209,209,209)' }}>
                                {t('document.privacy')}
                            </a>
                            <span className="mx-1">&bull;</span>
                            <a href="/document/TermsConditions" target="_blank" rel="noopener noreferrer" className="truncate max-w-[90px]" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'inline-block', color: 'rgb(209,209,209)' }}>
                                {t('document.terms')}
                            </a>
                        </div>
                    ) : (
                        <div className="flex flex-col items-center gap-4 mt-4">
                            <a href="/document/privacy" target="_blank" rel="noopener noreferrer" className={`${!isMobile ? (sidebarCollapsed ? 'w-[85%] ml-[7.5%]' : 'w-[85%] ml-[7.5%]') + ' rounded-lg border border-[rgb(54,54,54)] px-3 py-2' : 'border-b border-gray-600 rounded-none px-8 py-2'} flex items-center justify-center`} title={t('document.privacy')} style={{ color: 'rgb(209,209,209)' }}>
                                <i className="fas fa-user-secret text-[1.4rem]"></i>
                            </a>
                            <a href="/document/TermsConditions" target="_blank" rel="noopener noreferrer" className={`${!isMobile ? (sidebarCollapsed ? 'w-[85%] ml-[7.5%]' : 'w-[85%] ml-[7.5%]') + ' rounded-lg border border-[rgb(54,54,54)] px-3 py-2' : 'border-b border-gray-600 rounded-none px-8 py-2'} flex items-center justify-center`} title={t('document.terms')} style={{ color: 'rgb(209,209,209)' }}>
                                <i className="fas fa-file-contract text-[1.4rem]"></i>
                            </a>
                        </div>
                    )}
                </div>
            </aside>

            {/* Login Modal */}
            <LoginModal
                show={showLoginModal}
                onClose={closeLoginModal}
                onLoginSuccess={handleLoginSuccess}
                activeTab={activeTab}
                initialRegister={isRegisterMode}
            />

            <ContactUsModal show={showContactUsModal} onClose={() => setShowContactUsModal(false)} />

            {/* 退出登录确认弹窗 */}
            <LogoutConfirmModal
                show={showLogoutConfirm}
                onClose={cancelLogout}
                onConfirm={confirmLogout}
            />
        </>
    );
};

export default Sidebar; 